package cn.aj.pet.service.impl;

import cn.aj.basic.utils.BaiduAuditUtils;
import cn.aj.basic.utils.DistanceUtil;
import cn.aj.basic.utils.Point;
import cn.aj.org.domain.Shop;
import cn.aj.org.mapper.ShopMapper;
import cn.aj.pet.domain.SearchMasterMsg;
import cn.aj.pet.domain.SearchMasterMsgAuditLog;
import cn.aj.pet.dto.PublishDto;
import cn.aj.pet.mapper.SearchMasterMsgAuditLogMapper;
import cn.aj.pet.service.ISearchMasterMsgService;
import cn.aj.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author aj
 * @since 2022-12-07
 */
@Service
public class SearchMasterMsgServiceImpl extends BaseServiceImpl<SearchMasterMsg> implements ISearchMasterMsgService {

    @Autowired
    private ShopMapper shopMapper;

    @Autowired
    private SearchMasterMsgAuditLogMapper searchMasterMsgAuditLogMapper;


    /**
    * @Title: publish
    * @Description: TODO
    * @Author: Mr.GT
    * @Version: 1.0
    * @Date:  2022/12/7 0007 15:47
    * @Parameters: [publishDto]
    * @Return void
     * 宠物寻主
    */
    @Override
    public void publish(PublishDto publishDto) {
        // 参数校验 dto注解完成
        // 保存数据
        SearchMasterMsg searchMasterMsg = new SearchMasterMsg();
        // 工具类设置
        BeanUtils.copyProperties(publishDto, searchMasterMsg);
        searchMasterMsg.setState(0); // 给宠物设置一个状态表示处理
        // 获取保存数据的id
        searchMasterMsg.setId(searchMasterMsg.getId());
        super.add(searchMasterMsg);
        // 数据库的数据脏了,不做保存用户user_id
        // 百度ai审核直接,保存日志
        if(!BaiduAuditUtils.TextCensor(publishDto.getName())) { // 审核宠物名
            SearchMasterMsgAuditLog searchMasterMsgAuditLog = new SearchMasterMsgAuditLog();
            searchMasterMsgAuditLog.setMsgId(searchMasterMsg.getId());
            searchMasterMsgAuditLog.setState(2); // 审核失败
            searchMasterMsgAuditLog.setAuditId(-1L);
            searchMasterMsgAuditLog.setAuditTime(new Date());
            searchMasterMsgAuditLog.setNote("该宠物名字为:" + publishDto.getName()+"," +"审核失败");
            searchMasterMsgAuditLogMapper.add(searchMasterMsgAuditLog);
        } else { // 审核通过, 分配店铺，修改状态,调用百度地图工具类
            // 获取店铺坐标
            Point point = DistanceUtil.getPoint(searchMasterMsg.getAddress());
            List<Shop> shops= shopMapper.loadAll();
            Shop nearestShop = DistanceUtil.getNearestShop(point, shops);
            searchMasterMsg.setState(1); // 设置状态为1已经通过
            if(nearestShop != null) {
                // 设置店铺信息
                searchMasterMsg.setShopId(nearestShop.getId());
            }
            super.update(searchMasterMsg);
        }
    }
}
